import { Command } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import { AutomationEngine } from '../modules/automation-engine';
import { config, validateConfig } from '../config';
import { logger } from '../utils/logger';
import { SSHConfig, AutomationTask } from '../types';

interface CLIOptions {
  host?: string;
  port?: number;
  username?: string;
  password?: string;
  interactive?: boolean;
}

export class CLI {
  private program: Command;
  private engine: AutomationEngine | null = null;

  constructor() {
    this.program = new Command();
    this.setupCommands();
  }

  private setupCommands(): void {
    this.program
      .name('ssh-claude-automation')
      .description('自动化SSH远程运维和部署系统')
      .version('1.0.0');

    this.program
      .command('connect')
      .description('连接到远程SSH服务器')
      .option('-h, --host <host>', 'SSH主机地址')
      .option('-p, --port <port>', 'SSH端口', '22')
      .option('-u, --username <username>', '用户名')
      .option('-w, --password <password>', '密码')
      .option('-i, --interactive', '交互式输入连接信息')
      .action(this.handleConnect.bind(this));

    this.program
      .command('task')
      .description('执行自动化任务')
      .argument('<description>', '任务描述')
      .option('-i, --interactive', '交互式确认命令')
      .action(this.handleTask.bind(this));

    this.program
      .command('command')
      .description('执行单个命令')
      .argument('<command>', '要执行的命令')
      .action(this.handleCommand.bind(this));

    this.program
      .command('status')
      .description('显示连接和任务状态')
      .action(this.handleStatus.bind(this));

    this.program
      .command('tasks')
      .description('列出所有任务')
      .option('-s, --status <status>', '按状态过滤 (pending|running|completed|failed)')
      .action(this.handleTasks.bind(this));

    this.program
      .command('disconnect')
      .description('断开SSH连接')
      .action(this.handleDisconnect.bind(this));

    this.program
      .command('interactive')
      .description('进入交互式模式')
      .action(this.handleInteractive.bind(this));
  }

  private async handleConnect(options: CLIOptions): Promise<void> {
    try {
      let sshConfig: SSHConfig;

      if (options.interactive) {
        sshConfig = await this.promptSSHConfig();
      } else {
        sshConfig = {
          host: options.host || config.ssh.host,
          port: parseInt(String(options.port)) || config.ssh.port,
          username: options.username || config.ssh.username,
          password: options.password || config.ssh.password,
          timeout: config.ssh.timeout
        };
      }

      if (!sshConfig.host || !sshConfig.username || !sshConfig.password) {
        console.log(chalk.red('❌ 缺少必要的连接参数'));
        return;
      }

      console.log(chalk.yellow('🔌 正在连接SSH服务器...'));

      this.engine = new AutomationEngine(sshConfig, config.deepseek);
      await this.engine.initializeSSHConnection(sshConfig);

      console.log(chalk.green(`✅ 已连接到 ${sshConfig.username}@${sshConfig.host}:${sshConfig.port}`));

    } catch (error) {
      console.log(chalk.red(`❌ 连接失败: ${error}`));
      process.exit(1);
    }
  }

  private async handleTask(description: string, options: { interactive?: boolean }): Promise<void> {
    if (!this.engine || !this.engine.isConnected()) {
      console.log(chalk.red('❌ 请先连接SSH服务器'));
      return;
    }

    try {
      if (options.interactive) {
        console.log(chalk.yellow('🤖 正在分析任务...'));

        const { claudeResponse, taskId } = await this.engine.executeInteractiveTask(description);

        console.log(chalk.cyan('\n📋 DeepSeek分析结果:'));
        console.log(claudeResponse.reasoning);

        if (claudeResponse.commands && claudeResponse.commands.length > 0) {
          console.log(chalk.cyan('\n💻 建议执行的命令:'));
          claudeResponse.commands.forEach((cmd: string, index: number) => {
            console.log(chalk.white(`${index + 1}. ${cmd}`));
          });

          const { confirmed } = await inquirer.prompt([{
            type: 'confirm',
            name: 'confirmed',
            message: '是否执行这些命令?',
            default: false
          }]);

          if (confirmed) {
            console.log(chalk.yellow('⚡ 正在执行命令...'));
            const results = await this.engine.executeCommands(taskId, claudeResponse.commands);
            this.displayCommandResults(results);
          } else {
            console.log(chalk.gray('❌ 任务已取消'));
          }
        }
      } else {
        console.log(chalk.yellow('🤖 正在执行自动化任务...'));
        const task = await this.engine.executeAutomatedTask(description);
        this.displayTaskResult(task);
      }

    } catch (error) {
      console.log(chalk.red(`❌ 任务执行失败: ${error}`));
    }
  }

  private async handleCommand(command: string): Promise<void> {
    if (!this.engine || !this.engine.isConnected()) {
      console.log(chalk.red('❌ 请先连接SSH服务器'));
      return;
    }

    try {
      console.log(chalk.yellow(`⚡ 执行命令: ${command}`));
      const result = await this.engine.executeCustomCommand(command);
      this.displayCommandResults([result]);
    } catch (error) {
      console.log(chalk.red(`❌ 命令执行失败: ${error}`));
    }
  }

  private async handleStatus(): Promise<void> {
    if (!this.engine) {
      console.log(chalk.gray('🔌 未连接SSH服务器'));
      return;
    }

    const status = this.engine.getConnectionStatus();

    if (status.connected) {
      console.log(chalk.green('✅ SSH连接状态: 已连接'));
      console.log(chalk.cyan(`📍 会话ID: ${status.sessionId}`));

      if (status.sessionInfo) {
        console.log(chalk.cyan(`🖥️  服务器: ${status.sessionInfo.config.host}:${status.sessionInfo.config.port}`));
        console.log(chalk.cyan(`👤 用户: ${status.sessionInfo.config.username}`));
        console.log(chalk.cyan(`⏰ 最后活动: ${status.sessionInfo.lastActivity}`));
      }
    } else {
      console.log(chalk.red('❌ SSH连接状态: 未连接'));
    }

    const tasks = this.engine.getAllTasks();
    console.log(chalk.cyan(`\n📊 任务统计:`));
    console.log(`  总任务数: ${tasks.length}`);
    console.log(`  待执行: ${tasks.filter(t => t.status === 'pending').length}`);
    console.log(`  执行中: ${tasks.filter(t => t.status === 'running').length}`);
    console.log(`  已完成: ${tasks.filter(t => t.status === 'completed').length}`);
    console.log(`  已失败: ${tasks.filter(t => t.status === 'failed').length}`);
  }

  private async handleTasks(options: { status?: string }): Promise<void> {
    if (!this.engine) {
      console.log(chalk.gray('🔌 未连接SSH服务器'));
      return;
    }

    let tasks = this.engine.getAllTasks();

    if (options.status) {
      tasks = this.engine.getTasksByStatus(options.status as any);
    }

    if (tasks.length === 0) {
      console.log(chalk.gray('📝 没有任务'));
      return;
    }

    console.log(chalk.cyan('📋 任务列表:'));
    tasks.forEach((task, index) => {
      const statusIcon = this.getStatusIcon(task.status);
      const timeInfo = task.completedAt
        ? `完成于: ${task.completedAt.toLocaleString()}`
        : `创建于: ${task.createdAt.toLocaleString()}`;

      console.log(`\n${index + 1}. ${statusIcon} ${task.description}`);
      console.log(`   ID: ${task.id}`);
      console.log(`   ${timeInfo}`);
      console.log(`   命令数: ${task.commands.length}`);
      console.log(`   结果数: ${task.results.length}`);

      if (task.results.length > 0) {
        const successCount = task.results.filter(r => r.success).length;
        console.log(`   成功率: ${successCount}/${task.results.length}`);
      }
    });
  }

  private async handleDisconnect(): Promise<void> {
    if (!this.engine) {
      console.log(chalk.gray('🔌 未连接SSH服务器'));
      return;
    }

    try {
      await this.engine.disconnect();
      console.log(chalk.green('✅ SSH连接已断开'));
      this.engine = null;
    } catch (error) {
      console.log(chalk.red(`❌ 断开连接失败: ${error}`));
    }
  }

  private async handleInteractive(): Promise<void> {
    console.log(chalk.cyan('🚀 欢迎使用SSH-DeepSeek自动化系统'));

    while (true) {
      const { action } = await inquirer.prompt([{
        type: 'list',
        name: 'action',
        message: '请选择操作:',
        choices: [
          { name: '🔌 连接SSH服务器', value: 'connect' },
          { name: '🤖 执行自动化任务', value: 'task' },
          { name: '💻 执行单个命令', value: 'command' },
          { name: '📊 查看状态', value: 'status' },
          { name: '📋 查看任务列表', value: 'tasks' },
          { name: '🔌 断开连接', value: 'disconnect' },
          { name: '❌ 退出', value: 'exit' }
        ]
      }]);

      try {
        switch (action) {
          case 'connect':
            await this.handleConnect({ interactive: true });
            break;
          case 'task':
            if (!this.engine || !this.engine.isConnected()) {
              console.log(chalk.red('❌ 请先连接SSH服务器'));
              break;
            }
            const { taskDesc } = await inquirer.prompt([{
              type: 'input',
              name: 'taskDesc',
              message: '请输入任务描述:'
            }]);
            await this.handleTask(taskDesc, { interactive: true });
            break;
          case 'command':
            if (!this.engine || !this.engine.isConnected()) {
              console.log(chalk.red('❌ 请先连接SSH服务器'));
              break;
            }
            const { cmd } = await inquirer.prompt([{
              type: 'input',
              name: 'cmd',
              message: '请输入命令:'
            }]);
            await this.handleCommand(cmd);
            break;
          case 'status':
            await this.handleStatus();
            break;
          case 'tasks':
            await this.handleTasks({});
            break;
          case 'disconnect':
            await this.handleDisconnect();
            break;
          case 'exit':
            if (this.engine) {
              await this.engine.cleanup();
            }
            console.log(chalk.green('👋 再见!'));
            process.exit(0);
        }
      } catch (error) {
        console.log(chalk.red(`❌ 操作失败: ${error}`));
      }

      console.log(''); // 空行分隔
    }
  }

  private async promptSSHConfig(): Promise<SSHConfig> {
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'host',
        message: 'SSH主机地址:',
        default: config.ssh.host
      },
      {
        type: 'number',
        name: 'port',
        message: 'SSH端口:',
        default: config.ssh.port
      },
      {
        type: 'input',
        name: 'username',
        message: '用户名:',
        default: config.ssh.username
      },
      {
        type: 'password',
        name: 'password',
        message: '密码:',
        mask: '*'
      }
    ]);

    return {
      host: answers.host,
      port: answers.port,
      username: answers.username,
      password: answers.password,
      timeout: config.ssh.timeout
    };
  }

  private displayTaskResult(task: AutomationTask): void {
    const statusIcon = this.getStatusIcon(task.status);
    console.log(`\n${statusIcon} 任务${task.status === 'completed' ? '完成' : '失败'}: ${task.description}`);

    if (task.results.length > 0) {
      console.log(chalk.cyan('\n📝 执行结果:'));
      this.displayCommandResults(task.results);
    }
  }

  private displayCommandResults(results: any[]): void {
    results.forEach((result, index) => {
      const icon = result.success ? '✅' : '❌';
      console.log(`\n${icon} 命令 ${index + 1}: ${result.command}`);

      if (result.stdout) {
        console.log(chalk.green('📤 输出:'));
        console.log(result.stdout);
      }

      if (result.stderr) {
        console.log(chalk.red('🚨 错误:'));
        console.log(result.stderr);
      }

      console.log(chalk.gray(`退出码: ${result.exitCode} | 时间: ${result.timestamp.toLocaleString()}`));
    });
  }

  private getStatusIcon(status: string): string {
    switch (status) {
      case 'pending': return '⏳';
      case 'running': return '🔄';
      case 'completed': return '✅';
      case 'failed': return '❌';
      default: return '❓';
    }
  }

  public async run(): Promise<void> {
    try {
      validateConfig();
      await this.program.parseAsync();
    } catch (error) {
      console.log(chalk.red(`❌ 启动失败: ${error}`));
      process.exit(1);
    }
  }
}